package com.haoxuer.discover.pays.plugins.weiapppay;

import com.haoxuer.discover.pay.utils.MapUtils;
import com.haoxuer.discover.pay.weixin.domain.UnifiedOrderPayBack;
import com.haoxuer.discover.pay.weixin.domain.UnifiedOrderPayData;
import com.haoxuer.discover.pay.weixin.impl.PayWeiXinService;
import com.haoxuer.discover.pays.api.domain.simple.WeiXinPaySimple;
import com.haoxuer.discover.pays.plugins.base.PaymentPlugin;
import com.haoxuer.discover.pays.plugins.domain.PayBack;
import com.haoxuer.discover.pays.plugins.domain.PayInfo;
import com.haoxuer.discover.pays.plugins.weixinpay.WeiXinPaymentPlugin;
import com.haoxuer.discover.plug.data.entity.PluginConfig;
import com.haoxuer.discover.user.word.AdaptiveRandomWordFactory;
import jodd.util.StringUtil;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import static com.haoxuer.discover.pay.weixin.impl.PayWeiXinService.MD5Encode;

/**
 * 微信小程序支付.
 */
@Component("weiAppPaymentPlugin")
public class WeiAppPaymentPlugin extends PaymentPlugin {
  @Override
  public String getName() {
    return "微信小程序支付";
  }
  
  @Override
  public String getVersion() {
    return "1.01";
  }
  
  @Override
  public String getAuthor() {
    return "ada";
  }
  
  @Override
  public String getSiteUrl() {
    return "";
  }
  
  @Override
  public String getInstallUrl() {
    return "admin/plugin_payment/weiapppayment/install.htm";
  }
  
  @Override
  public String getUninstallUrl() {
    return "admin/plugin_payment/weiapppayment/uninstall.htm";
  }
  
  @Override
  public String getSettingUrl() {
    return "admin/plugin_payment/weiapppayment/setting.htm";
  }

  @Override
  public String getBaseUrl() {
    return "admin/plugin_pay/";
  }

  @Override
  public String viewName() {
    return "wxAppPay";
  }

  public static String getNonceStr() {
    return UUID.randomUUID().toString().replace("-", "").toLowerCase();
  }
  
  public static String getOrderNo() {
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    AdaptiveRandomWordFactory f = new AdaptiveRandomWordFactory();
    f.setMinLength(8);
    f.setMaxLength(8);
    f.setCharacters("1234567890");
    return format.format(new Date()) + "" + f.getNextWord();
  }
  
  @Override
  public PayBack pay(PayInfo payinfo) {
    PayBack result = new PayBack();
    
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
      UnifiedOrderPayData data = new UnifiedOrderPayData();
      String appid = pluginConfig.getAttribute("appkey");
      String mchid = pluginConfig.getAttribute("mch_id");
      String key = pluginConfig.getAttribute("key");
      String notify_url=pluginConfig.getAttribute("notify_url");
      data.setAppid(appid);
      data.setMch_id(mchid);
      data.setNonce_str(getNonceStr());
      
      data.setBody(payinfo.getBody());
      
      
      data.setOut_trade_no(getOrderNo());
      data.setTotal_fee(payinfo.getMoney().multiply(new BigDecimal(100)).intValue());
      if (StringUtil.isNotEmpty(payinfo.getIp())){
        data.setSpbill_create_ip(payinfo.getIp());
      }else {
        data.setSpbill_create_ip("123.12.12.123");
      }
      data.setNotify_url(notify_url);
      data.setTrade_type("JSAPI");//APP  JSAPI
      data.setOpenid(payinfo.getOpenid());
      PayWeiXinService service = new PayWeiXinService(key);
      UnifiedOrderPayBack back = service.order(data);
      if (back.getReturn_code().equals("SUCCESS")) {
        result.setNo(back.getPrepay_id());
        result.setOrderNo(data.getOut_trade_no());
      } else {
        result.setCode(-301);
        result.setMsg(back.getReturn_msg());
      }
    }
    return result;
  }
  
  @Override
  public WeiXinPaySimple handle(PayBack back) {
    WeiXinPaySimple result = new WeiXinPaySimple();
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
      String appid = pluginConfig.getAttribute("appkey");
      String mchid = pluginConfig.getAttribute("mch_id");
      String key = pluginConfig.getAttribute("key");
      String packageinfo=pluginConfig.getAttribute("packageinfo");
      result.setAppid(appid);
      result.setNoncestr(getNonceStr());
      result.setPackageInfo("prepay_id="+ back.getNo());
      result.setTimestamp("" + WeiXinPaymentPlugin.second());
      result.setPrepayid(back.getNo());
      result.setPartnerid(mchid);
      result.setSignType("MD5");
  
      Map<String, String> map = MapUtils.getSortMap();
      map.put("appId", result.getAppid());
      map.put("package", result.getPackageInfo());
      map.put("nonceStr", result.getNoncestr());
      map.put("timeStamp", result.getTimestamp());
      map.put("signType", result.getSignType());
  
      String p = MapUtils.params(map);
      p = p + "&key=" + key;
      System.out.println(p);
      String sign = MD5Encode(p);
      result.setSign(sign);
    }
    return result;
  }
}
